package com.linewell.license.demo.security;

import com.alibaba.fastjson.JSONObject;
import com.linewell.license.demo.bean.UserDetail;
import com.linewell.license.demo.utils.CurrentRequestUtils;
import com.linewell.license.platform.common.model.result.ResultCodeBaseConstants;
import com.linewell.license.platform.common.model.result.ResultObjectModel;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author
 * Company:
 * Createtime : 2018年9月11日 下午3:40:02
 * Description : 认证成功后的动作
 */
@Component
public class SecurityLoginSuccessHandler implements AuthenticationSuccessHandler {

	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
		this.handler(request, response, authentication);
	}

	private void handler(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8");
		Object principal = authentication.getPrincipal();
		UserDetail detail = (UserDetail) principal;
		CurrentRequestUtils.setLoginInfo(detail.getUser());
		String targetUrl = CurrentRequestUtils.getRequestContextPath(request)+"/index.html";
		if(!CurrentRequestUtils.isAjaxRequest()) {
			response.sendRedirect(targetUrl);
			return;
		}
		ResultObjectModel<Object> result = new ResultObjectModel<>(ResultCodeBaseConstants.SUCCESS, "登录成功" , targetUrl);
		response.getWriter().println(JSONObject.toJSONString(result));
	}

}
